package com.web.helper.calculation;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.web.helper.Caculate;
import io.github.coho04.githubapi.Github;
import io.github.coho04.githubapi.entities.GHUser;

import static com.common.constant.Token.GITHUB_TOKEN;

/**
 * 获取用户标星数
 */
public class CaculateStart implements Caculate {

    public int process(String username) {
        Github g = new Github(GITHUB_TOKEN);
        GHUser user = g.findUserByName(username);
        String lastPage = "0";


        String originalUrl =  user.getStarredUrl();
        String url = originalUrl.replace("{/owner}{/repo}", "")
                + "?per_page=1";

        // 使用Hutool发送GET请求并获取响应
        HttpResponse response = HttpUtil.createGet(url).execute();

        // 获取Link响应头
        String linkHeader = response.header("Link");

        if (linkHeader != null) {
            // 使用正则表达式提取 last 页的 page 参数值
            lastPage = linkHeader.replaceAll(".*page=(\\d+)>; rel=\"last\".*", "$1");
            System.out.println("Last page number: " + lastPage);
        } else {
            System.out.println("Link header not found");
        }

        return Integer.parseInt(lastPage);
    }
}
